package com.tuling.learnmongodb.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.mongodb.client.result.DeleteResult;
import com.tuling.learnmongodb.model.Logistic;
import com.tuling.learnmongodb.model.Order;
import com.tuling.learnmongodb.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void addOrder(Order order) {
        // 雪花算法生成订单id
        order.setId(IdUtil.getSnowflake(1,1).nextIdStr());
        // 设置订单状态
        order.setStatus("已下单");
        // 下单时间
        order.setOrderTime(new Date());
        // 发货时间
        order.setShipTime(new Date());
        // 添加订单到mongodb
        mongoTemplate.insert(order, "order");
    }

    @Override
    public void updateOrderAndLogistaics(Logistic logistic) {
        // 获取操作名称
        String status = logistic.getOperation();
        // 设置操作时间
        logistic.setOperationTime(new Date());
        // 初始化Query对象，根据订单编号查询
        Query query = new Query(Criteria.where("_id").is(logistic.getOrderId()));
        // 初始化 update 对象
        Update update = new Update();
        // 更新订单状态
        update.set("status", status);
        // 追加物流信息
        update.push("logistics", logistic);
        // 更新订单信息
        mongoTemplate.upsert(query, update, Order.class, "order");
    }

    @Override
    public Order selectOrderById(String id) {
        Query query = new Query((Criteria.where("_id").is(id)));
        return mongoTemplate.findOne(query, Order.class, "order");
    }

    @Override
    public List<Order> selectOrderList() {
        return mongoTemplate.findAll(Order.class, "order");
    }

    @Override
    public boolean deleteOrderById(String id) {
        // 初始化Query对象，根据订单编号查询
        Query query = new Query(Criteria.where("_id").is(id));
        DeleteResult result = mongoTemplate.remove(query, Order.class, "order");
        return result.getDeletedCount() > 0 ? true:false;
    }
}
